# coding = utf-8
import urllib.request
import re
import requests
import socks
requests.adapters.DEFAULT_RETRIES = 5
def getDatas(keyword, pages):
    params = []
    for i in range(30,30*pages+30,30):
        params.append({
            'tn': 'resultjson_com',
            'ipn': 'rj',
            'ct': 201326592,
            'is': '',
            'fp': 'result',
            'queryWord': keyword,
            'cl': 2,
            'lm': -1,
            'ie': 'utf-8',
            'oe': 'utf-8',
            'adpicid': '',
            'st': -1,
            'z': '',
            'ic': 0,
            'word': keyword,
            's': '',
            'se': '',
            'tab': '',
            'width': '',
            'height': '',
            'face': 0,
            'istype': 2,
            'qc': '',
            'nc': 1,
            'fr': '',
            'pn': i,
            'rn': 30,
            'gsm': '1e',
            '1575080574755': ''
        })
        headers = {
            'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.87 Safari/537.36',
           # 'Referer':'http://image.baidu.com/search/index?tn=baiduimage&ct=201326592&lm=-1&cl=2&ie=gb18030&word=%CD%B7%CF%F1&fr=ala&oriquery=%E5%A4%B4%E5%83%8F&ala=1&alatpl=portait&pos=0'
             'Referer':'http://image.baidu.com/search/index?tn=baiduimage&ct=201326592&lm=-1&cl=2&ie=gb18030&word=%CD%B7%CF%F1&fr=ala&oriquery=%E5%A4%B4%E5%83%8F&ala=1&alatpl=portait&pos=0',
            'X-Requested-With':'XMLHttpRequest'
        }
        ip_port = '117.40.103.206:14865'
        proxy = {
            'http': 'socks5://{}'.format(ip_port),
            'https': 'socks5://{}'.format(ip_port)
        }
        print(proxy)
        url = "http://image.baidu.com/search/index?tn=baiduimage&ct=201326592&lm=-1&cl=2&ie=gb18030&word=%CD%B7%CF%F1&fr=ala&oriquery=%E5%A4%B4%E5%83%8F&ala=1&alatpl=portait&pos=0"
    urls = []
    for i in params:
        urls.append(requests.get(url, params=i,headers=headers,proxies=proxy).json().get("data"))
    return urls
def getImg(datalist, path):
    x = 0
    for list in datalist:
        for i in list:
            if i.get('thumbURL') != None:
                print('%s' % i.get('thumbURL'))
                urllib.request.urlretrieve(i.get('thumbURL'), path + '%d.jpg' % x)
                x += 1
            #else:
            #    print('图片链接不存在')


if __name__ == '__main__':
    datalist = getDatas('头像', 1)
    getImg(datalist, 'D:/python/qqimage/images/纹身/')